package com.zky.Aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component
@Slf4j
@Aspect
public class LogStatisticAspect {
    @Pointcut("execution(* com.zky..controller..*(..))")
    public void controllerMethod() {}

    @Around("controllerMethod()")
    public Object logStatistic(ProceedingJoinPoint joinPoint) throws Throwable {
            //获取起始时间
            long start = System.currentTimeMillis();
            //获取 方法名加参数
            String className = joinPoint.getSignature().getDeclaringTypeName();
            String methodName = joinPoint.getSignature().getName();
            Object[] args = joinPoint.getArgs();
        try {
            Object result = joinPoint.proceed();
            long cost = System.currentTimeMillis()-start;
            log.info("【日志统计】方法: {}.{}，参数: {}，耗时: {} ms，返回: {}",
                    className, methodName, Arrays.toString(args), cost, result);
            return result;
        } catch (Throwable e) {
            long cost = System.currentTimeMillis() - start;
            log.error("【日志统计】方法: {}.{}，参数: {}，耗时: {} ms，异常: {}",
                    className, methodName, Arrays.toString(args), cost, e.getMessage(), e);
            throw e;
        }
    }
}
